from rest_framework import serializers
from rest_framework.exceptions import ValidationError
from home import models
from rest_framework.exceptions import AuthenticationFailed

class UserLoginModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.UserModel
        fields = ['username','role','phoneNumber','realName','id','password']
        extra_kwargs = {
            'id':{
                'read_only':True,
            },
            'password':{
                'write_only':True
            }
        }

    def validate_phoneNumber(self,value):
        if len(value) !=11:
            raise ValidationError('手机号码验证失败！！！')
        if models.UserModel.objects.filter(phoneNumber=value).first():
            raise ValidationError('手机号码已经存在了！！！')
        return value

    def validate_username(self,value):
        if len(value)>20:
            raise ValidationError('用户名长度过长')
        name = 'abqwertyuiopasdfghjklzxcvbnm1234567890'
        for key  in value:
            if key not in name:
                raise ValidationError('用户名必须由小写字母数字组成')
        if models.UserModel.objects.filter(username=value).first():
            raise ValidationError('账户已经存在了，无法注册')
        return value

    def validate_role(self,value):
        if value not in [1,2,'1','2']:
            raise ValidationError('用户角色有问题')
        if models.UserModel.objects.filter(role=1).first() and value==1:
            raise ValidationError('管理员账户已经存在了')
        return value

    def create(self,validated_data):
        #拿到传递进来的request
        request = self.context.get('request')
        try:
            models.UserModel.objects.create(**validated_data)
        except Exception as e:
            raise ValidationError(str(e))
        return validated_data




